﻿using SqlSugar;
using System;
using WebApiOrm.Provider;
using WebApiOrm.Provider.SqlSugar;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// OrmBuilder扩展
    /// 扩展添加具体的Orm
    /// </summary>
    public static class OrmBuilderExtensions
    {
        /// <summary>
        /// 添加SqlSugar的Orm
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="ormName"></param>
        /// <returns></returns>
        public static IOrmBuilder AddSqlSugar(this IOrmBuilder builder, string ormName)
        {
            builder.Services.AddOrmProvider<SqlSugarOrmProvider>(ormName);
            builder.Services.AddScoped<ISqlSugarClient>(serviceProvider =>
            {
                var dbType = builder.DatabaseType switch
                {
                    DatabaseType.Sqlite => DbType.Sqlite,
                    DatabaseType.SqlServer => DbType.SqlServer,
                    DatabaseType.PostgreSQL => DbType.PostgreSQL,
                    _ => throw new NotSupportedException(),
                };

                return new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = dbType,
                    ConnectionString = builder.ConnectionString,
                    IsAutoCloseConnection = true,
                    MoreSettings = new ConnMoreSettings { PgSqlIsAutoToLower = false }
                });
            });
            return builder;
        }
    }
}
